package com.manpower.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 获取 redis的string类型
    public <T> T get(String keyId, Class<T> clazz) {
        String key = keyId;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            return null;
        }
        try {
            return objectMapper.readValue(objectMapper.writeValueAsString(obj), clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    // 获取 redis的string类型
    public <T> T get(Integer keyId, Class<T> clazz) {
        String key = clazz.getSimpleName() + ":" + keyId;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            return null;
        }
        try {
            return objectMapper.readValue(objectMapper.writeValueAsString(obj), clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    // 设置 redis的string类型
    public <T> boolean put(String keyId, T t, long timeout) {
        try {
            String key = keyId;
            if (timeout < 1) {
                redisTemplate.opsForValue().set(key, t);
            } else {
                redisTemplate.opsForValue().set(key, t, timeout, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 设置 redis的string类型
    public <T> boolean put(Integer keyId, T t, long timeout) {
        try {
            String key = t.getClass().getSimpleName() + ":" + keyId;
            if (timeout < 1) {
                redisTemplate.opsForValue().set(key, t);
            } else {
                redisTemplate.opsForValue().set(key, t, timeout, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 删除 redis的string类型
    public <T> boolean del(Integer keyId, Class<T> clazz) {
        String key = clazz.getSimpleName() + ":" + keyId;
        Boolean delete = redisTemplate.delete(key);
        return delete == null || delete;
    }

}
